package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.ex.LoginException;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Controller
public class LoginController extends BaseController{
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private HttpServletRequest request;

    public HttpServletRequest request(){
//        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public HttpSession session(){
        return request().getSession();
    }

    public String forward(String url){
        return UrlBasedViewResolver.FORWARD_URL_PREFIX+url;
    }

    public String redirect(String url){
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX+url;
    }

    @GetMapping("/login")
    public String toLogin(){
        return forward("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account, @RequestParam("password") String password){
        SysUser loginUser= sysUserService.login(account,password);
        if (loginUser!=null){
//            session().setAttribute("loginUser",loginUser);
            session(Constants.SESSION_USER,loginUser);
            return redirect("/main/index");
        }else {
            throw new LoginException("登录失败，用户名或者密码错误！");
        }
    }

    @GetMapping("/ex")
    public void throwException(){
        throw new RuntimeException("测试不同异常映射到不同页面！");
    }

    @GetMapping("/main/index")
    public String index(){
        return "index";
    }

//    @ExceptionHandler(value = RuntimeException.class)
    public String handlerException(RuntimeException e,HttpServletRequest request){
        request.setAttribute(Constants.REQUEST_ERROR,e);
        return "500";
    }

    @GetMapping("/logout")
    public String logout() {
        session().invalidate();
        return redirect("/login");
    }
}
